package exam.exam1;

import java.io.*;
import java.text.DecimalFormat;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test1 {
    public static void main(String[] args) throws IOException {
        //文件地址
        File src1 = new File("E:\\javaSE进阶笔记\\day15\\AAA\\JavaSE进阶-考试01.png");
        File src2 = new File("E:\\大数据技术与应用专业考核题库.doc");
        //创建线程池
        ExecutorService es = Executors.newFixedThreadPool(5);
        //创建线程类对象
        MyRun m1 = new MyRun(src1);
        MyRun m2 = new MyRun(src2);
        //提交线程池
        es.submit(m1);
        es.submit(m2);
        //关闭线程池
        es.shutdown();
    }
}


class MyRun implements Runnable{
    private File src;

    public MyRun(File src) {
        this.src = src;
    }

    @Override
    public void run() {
        try {
            //创建字节输入缓冲流对象
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
            //获取传入文件的后缀名
            String name = src.getName();
            String[] split = name.split("\\.");
            String type = split[split.length-1];
            //创建字节输出缓冲流对象
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream("day15\\"+ UUID.randomUUID()+"."+type));
            //创建浮点数格式，也就是百分比
            DecimalFormat df = new DecimalFormat("##%");
            //获取文件大小
            long length = src.length();
            //一次读arr个数组的字节
            byte[] arr = new byte[1024*2];
            int len;    //实际一次读了多少字节
            int sum = 0;    //每次读写后需要将读到的字节累加
            System.out.println(src.getName()+":"+length);
            while ((len = bis.read(arr)) != -1){
                Thread.sleep(50);
                sum += len;
                //复制文件
                bos.write(arr,0,len);
                bos.flush();
                //format即复制的进度
                String format = df.format(1.0 * sum / length);
                System.out.println(src.getName()+"文件复制了："+format);
            }
            System.out.println(src.getName()+"文件上传成功了");
            //释放资源
            bis.close();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
